const ws = require('nodejs-websocket')
const POST = 8010
let old = '' // 保存原来的值
const server = ws.createServer(connect => {
  connect.on('text', data => {
    if (data !== old && data !== 'rub') { // 与上一次的值不相等
      console.log('received: ' + data)
      old = data
      broadcast(data)
    }
  })
  connect.on('close', (code, reason) => {
    console.log('connection closed!')
  })

  connect.on('error', () => {
    console.log('connection error!')
  })
  // 广播,给所有的用户发送消息  connections(这个数组里,保存了每个连接)
  function broadcast (msg) {
    console.log(server.connections.length)
    server.connections.forEach(connect => {
      connect.send(msg)
    })
  }
})

server.listen(POST, () => {
  console.log('websocket server start success!')
})
